﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Text;
using System.Security.Principal;
using System.IO;
using System.Security.Cryptography;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(Request.QueryString["logoff"]) == false && Request.QueryString["logoff"].ToLowerInvariant() == "true")
        {
            FormsAuthentication.SignOut();
            ErrorMessage.Text = "You have been signed out";
            ErrorMessage.Visible = true;
        }
    }

    protected void LogIn_Clicked(object sender, EventArgs e)
    {
        string username = tb_login.Text;
        string password = tb_password.Text;
        bool remember = RememberMe.Checked;

        _User user = new _User();

        string Id = user.Login(username, password);

        if (Id != null)
        {
            // Create the cookie that contains the forms authentication ticket
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(Id, RememberMe.Checked);

            // Get the FormsAuthenticationTicket out of the encrypted cookie
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

            // Create a new FormsAuthenticationTicket that includes our custom User Data
            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, Id.ToString());

            // Update the authCookie's Value to use the encrypted version of newTicket
            authCookie.Value = FormsAuthentication.Encrypt(newTicket);

            // Manually add the authCookie to the Cookies collection
            Response.Cookies.Add(authCookie);

            // Determine redirect URL and send user there
            string redirUrl = FormsAuthentication.GetRedirectUrl(Id, RememberMe.Checked);
            Response.Redirect(redirUrl);
        }

        if (FormsAuthentication.Authenticate(username, password))
        {
            FormsAuthentication.RedirectFromLoginPage(username, createPersistentCookie: remember);
        }
        else
        {
            ErrorMessage.Visible = true;
        }
    }
}